(function ($) {
    window.onload = function () {
        //如果不是编辑界面，那么就不执行下面的操作
        var is_list_view = true;
        if (window.location.pathname == '/storage/sound/') {
            showSystemSounds();
            return;
        } else {
            $('#id_name').attr("disabled", true);
            $('.submit-row').click(beforeSubmit);

            is_list_view = false;
            $('#id_name').after('<input type="file" id="upload_sound" name="file" multiple="multiple"/>') //插入按钮
            $('#upload_sound').css("marginLeft", "8px")
            $('#upload_sound').change({ type: "sound" }, handleUpload);
            
            initSystemSounds();
        }

        function beforeSubmit(evt) {
            $('#id_name').attr("disabled", false);
        }

        function showSystemSounds() {
            firebase.initializeApp(config);

            var auth = firebase.auth();
            storageRef = firebase.storage().ref();

            $('#content-main').after('<div id="my_container" class="flex"><input type="file" id="upload_file" name="file" multiple="multiple"/>' +
                '<label id="process"></label></div>')
            $('#upload_file').css('float', 'left')
            $('#upload_file').change(handleFilesSelect);
            document.getElementById('upload_file').disabled = true;

            auth.onAuthStateChanged(function (user) {
                if (user) {
                    console.log('Anonymous user signed-in.', user);
                    // document.getElementById('upload_file').disabled = false;
                } else {
                    console.log('There was no anonymous session. Creating a new anonymous user.');
                    auth.signInAnonymously();
                }
            });
        }

        function initSystemSounds() {
            firebase.initializeApp(config);

            var auth = firebase.auth();
            storageRef = firebase.storage().ref();

            document.getElementById('upload_sound').disabled = true;
            auth.onAuthStateChanged(function (user) {
                if (user) {
                    console.log('Anonymous user signed-in.', user);
                    document.getElementById('upload_sound').disabled = false;
                } else {
                    console.log('There was no anonymous session. Creating a new anonymous user.');
                    auth.signInAnonymously();
                }
            });
        }

        function handleFilesSelect(evt) {
            evt.stopPropagation();
            evt.preventDefault();

            let files = evt.target.files;
            if (files.length == 0) {
                return;
            }

            let count = 0;
            $("#process").html('uploading: ' + count + '/' + files.length);
            for (let index = 0; index < files.length; index++) {
                let file_index = index;
                const file = files[file_index];
                let metadata = {
                    'contentType': file.type
                };
                storageRef.child('diff/sounds/' + file.name).put(file, metadata).then(function (snapshot) {
                    $.get("/ajax/upload_sounds/", {'name': file.name, 'url': snapshot.downloadURL, 'md5': snapshot.metadata.md5Hash}, function (ret) {
                        count++;
                        $("#process").html('uploading: ' + count + '/' + files.length);
                        if (count == files.length) {
                            alert('Upload succeed.')
                            window.location.reload();
                        }
                    })
                }).catch(function (error) {
                    console.error('Upload failed:', error);
                    alert('Upload failed.')
                });
            }
        }

        function handleUpload(evt) {
            evt.stopPropagation();
            evt.preventDefault();

            let files = evt.target.files;
            for (let index = 0; index < files.length; index++) {
                const file = files[index];
                if (file.name.indexOf('a') != -1) {
                    uploadFile(file, 'sound_android');
                } else {
                    uploadFile(file, 'sound');
                }
            }
        }

        function uploadFile(file, type) {
            let metadata = {
                'contentType': file.type
            };

            document.getElementById('id_' + type).value = '';
            storageRef.child('diff/sounds/' + file.name).put(file, metadata).then(function (snapshot) {
                document.getElementById('id_' + type).value = snapshot.downloadURL;
                if (type == 'sound') {
                    $('#id_name').val(file.name);
                    document.getElementById('id_md5').value = snapshot.metadata.md5Hash;
                } else {
                    document.getElementById('id_md5_android').value = snapshot.metadata.md5Hash;
                }
            }).catch(function (error) {
                console.error('Upload failed:', error);
                alert('Upload failed.')
            });
        }
    }
})(django.jQuery);
